<?php

	class My_Plugin_Acl extends Zend_Controller_Plugin_Abstract
	{
		private $_acl;
		private $_auth;

		private $_noauth = array(
			'module' 	 => 'default',
			'controller' => 'user',
			'action' 	 => 'login'
		);

		private $_noacl = array(
			'module' 	 => 'default',
			'controller' => 'error',
			'action' 	 => 'denied'
		);

		private $_roles 	= array();
		private $_resources = array();
		private $_linkRole 	= null;
		private $_userRole	= null;
		private $_defaultUserRole	= 'guest';

		public function __construct($acl, $auth)
		{
			$this->_acl 	= $acl;
			$this->_auth 	= $auth;

			$this->_userRole = $this->_defaultUserRole;


	        $this->getRoles();
	        $this->setRoles();

//	        $this->getResources();
//	        $this->setResources();

			if ($this->_auth->hasIdentity()) {
				$this->_userRole = $this->_auth->getIdentity()->role;
			}

		}

		public function preDispatch(Zend_Controller_Request_Abstract $request)
		{

	        $frontController = Zend_Controller_Front::getInstance();
	        $dispatcher = $frontController->getDispatcher();

			$module 	= $request->getModuleName();
			$controller = $request->getControllerName();
			$action 	= $request->getActionName();

			$module 	= (!empty($module) ? $module : 'default');


			if (($module=='default') && ($controller == 'incoming-student') || ($module=='incoming-student') )  {
				$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
				return $redirector->setCode(301)->goto('index', 'index', 'incoming-students');
				//return $this->_redirect($url, array('code'=>301));
			}
			if (($module=='default') && ($controller == 'incoming-nomination') || ($module=='incoming-nomination') )  {
				$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
				return $redirector->setCode(301)->goto('index', 'index', 'foreign-students');
				//return $this->_redirect($url, array('code'=>301));
			}


			$resource 	= $module.':'.$controller;
			$moduleControllerAction = $module.':'.$controller.':'.$action;


            if (!$this->_acl->has($resource)) {
			    $this->_acl->addResource($resource);
            }


			if (!$dispatcher->isDispatchable($request)) {
				$module 	= 'default';
				$controller = 'error';
				$action 	= 'error';

				$resource 	= $module.':'.$controller;
			}


			//if ( ($resource != 'default:error') && ($module != 'webservices') ) {
			if ( ($resource != 'default:error') && ($moduleControllerAction != 'default:user:logout') ) {

				//DEFAULT ACCESS PERMISSIONS

				$this->_acl->deny();//deny everything
				$this->_acl->allow('developer');//allow developer for everything
				$this->_acl->allow('administrator');//allow system administrators/owners for everything

				/*
				$this->_acl->allow('guest', 'default:index');//allow guest role on default module's index controller/resource
				$this->_acl->allow('guest', 'default:error');//allow guest role on default module's error controller/resource
				$this->_acl->allow('guest', 'default:user', array('login', 'signup', 'activate', 'reset-password')); //allow guest role to login and signup
				$this->_acl->allow('guest', 'default:exchange', array('photo-upload'));
				$this->_acl->allow('guest', 'default:trainee', array('photo-upload'));
				*/
				//$this->_acl->allow('member', 'user', array('index', 'logout', 'change-password')); //allow member role to logout and user index



				$this->getLinkRole($module, $controller, $action);
				if (!empty($this->_linkRole)) {
					$this->_acl->allow($this->_linkRole, $resource, $action);
				}

				if (!$this->_acl->has($resource)) {
					$resource = null;
				}

				//TEST
		        //echo $this->_acl->isAllowed('guest', 'user', 'activate') ? 'allowed' : 'denied';//exit;
		        //echo $this->_acl->isAllowed('guest', 'admin', 'index') ? 'allowed' : 'denied';
		        //echo $this->_acl->isAllowed('member', 'admin', 'index') ? 'allowed' : 'denied';
		        //echo $this->_acl->isAllowed($this->_userRole, $resource, $action) ? 'allowed' : 'denied';


				if (!Zend_Registry::isRegistered('Zend_Acl')) {
					Zend_Registry::set('Zend_Acl', $this->_acl);
				}


				if (!$this->_acl->isAllowed($this->_userRole, $resource, $action)) {
                    if (CLIENT_NAME == 'demo') {
                        $mailMsg = '
                            SERVER: '.php_uname('n').'
                            CLIENT_NAME: '.CLIENT_NAME.'
                            file: '.__FILE__.'
                            line: '. __LINE__.'
                            isLoggedIn: '. ($this->_auth->hasIdentity() ? 'yes':'no').'
                            resource: '.$resource.'
                            module:   '.$request->getModuleName().'
                            controller:   '.$request->getControllerName().'
                            action:     '.$request->getActionName().'
                            pageRole: '.$this->_linkRole.'
                            userRole: '.$this->_userRole.'
                            userIP: '.$_SERVER['REMOTE_ADDR'].'
                        ';
                        $mailerObj = new Default_Model_Mailer();
                        $mailerObj->sendAlertMail('ACL-PLUGIN:unauthorized-entry', $mailMsg);
                    }

                    if (!$this->_auth->hasIdentity()) {

						$module 	= $this->_noauth['module'];
						$controller = $this->_noauth['controller'];
						$action 	= $this->_noauth['action'];

					} else {
						$module 	= $this->_noacl['module'];
						$controller = $this->_noacl['controller'];
						$action 	= $this->_noacl['action'];

					}
                    //echo "$module, $controller, $action";exit;

					$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
					$redirector->goto($action, $controller, $module);
					exit;

				}

				//echo $module, $controller, $action;
				$request->setModuleName($module)
						->setControllerName($controller)
						->setActionName($action);
				$request->isDispatched(false);

			}


		}

		public function postDispatch(Zend_Controller_Request_Abstract $request)
		{

		}

		public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
		{

		}

	    public function getLinkRole($module, $controller, $action)
	    {
			$model = new Default_Model_DbTable_Navigation();
	        $row = null;
	        if (!empty($module) && !empty($controller) && !empty($action)) {
	        	$row = $model->findNavigation($module, $controller, $action);

		        	if (empty($row)) {
                        $moduleDefaultRole = $model->getModuleDefaultRole($module);
		        		$data['module_name'] = $module;
		        		$data['controller_name'] = $controller;
		        		$data['action_name'] = $action;
		        		$data['role_name'] = (($moduleDefaultRole) ? $moduleDefaultRole : 'developer');
		        		$data['name'] = $module.'_'.$controller.'_'.$action;
		        		$data['is_external'] = '0';
		        		$newNavigation = $model->addNavigation($data);
		        	} else {
		        		$this->_linkRole = $row->role_name;
		        	}
	        }
	    }

	    public function getRoles()
	    {

	        $model = new Default_Model_DbTable_Role();
	        $rows = $model->fetchAll();
	        foreach ($rows as $key=>$role) {//echo $role->label;
	        	$roles[$role->id] = new stdClass();
	        	$roles[$role->id]->name = $role->name;
	        	$roles[$role->id]->parent = $role->parent;

	        	//$roles[$role->id]->id = $role->id;
	        	//$roles[$role->id]->label = $role->label;
	        	//$roles[$role->id]->parent_id = $role->parent_id;
	        }
	        $this->_roles = $roles;

	    }

	    public function setRoles()
	    {

	        foreach ($this->_roles as $key=>$role) {//echo $role->label;

	        	if (!$role->parent) {
			        $this->_acl->addRole($role->name);
			    } else {
			        $this->_acl->addRole($role->name, $role->parent);
			    }

	        }

	    }

	    /*

	    public function getResources()
	    {

			$model = new Default_Model_DbTable_Resource();
	        $rows = $model->fetchAll();
	        $resources = array();
	        foreach ($rows as $key=>$resource) {//echo $resources->label;
	        	$resources[$resource->id] = new stdClass();
	        	$resources[$resource->id]->id = $resource->id;
	        	$resources[$resource->id]->name = $resource->name;
	        	$resources[$resource->id]->label = $resource->label;
	        }
	        $this->_resources = $resources;

	    }

	    public function setResources()
	    {

	        foreach ($this->_resources as $key=>$resource) {//echo $resource->label;

        	    $this->_acl->addResource($resource->name);

	        }

	    }

	    public function getResourceActions($resource)
	    {

			$model = new Default_Model_DbTable_ResourceAction();
	        $rows = $model->findResourceActions($resource);
	        foreach ($rows as $key=>$action) {//echo $resources->label;
	        	$resourceActions[$action->id]->id = $action->id;
	        	$resourceActions[$action->id]->name = $action->name;
	        	$resourceActions[$action->id]->label = $action->label;
	        }
	        return $resourceActions;

	    }

	    public function setResourceActions($resourceActions)
	    {

	        //foreach ($resourceActions as $key=>$action) {//echo $resource->label;
        	    //$this->addResource($action->name);
	        //}

	    }
	    */




	}